<?php

namespace app\adminapi\controller;

use app\BaseController;
use think\facade\Cache;


class BaseApi extends BaseController
{
    public static $noVerify = ['Login\captcha','Login\index','Auth\read','Auth\save','Auth\delete','Auth\nav','Role\index','Auth\index','Role\delete',
        'Category\index'
    ];
    //初始化方法
    public function initialize()
    {
        parent::initialize();
        //允许的源域名
        header("Access-Control-Allow-Origin: *");
        //允许的请求头信息
        header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization");
        //允许的请求类型
        header('Access-Control-Allow-Methods: GET, POST, PUT,DELETE,OPTIONS,PATCH');
        $controllerPath = $this->request->controller().'\\'.$this->request->action();


        if(!in_array($controllerPath,self::$noVerify)){
            $token = isset($_SERVER['HTTP_AUTHORIZATION'])?$_SERVER['HTTP_AUTHORIZATION']:false;
            if(!$token){
                $this->fail('身份认证失效');
            }
            //验证token
            $tokenObjPath = \ClassAttr::getTokenClass();
            $jwtObj = \ClassAttr::initClass('jwtToken',$tokenObjPath);
            $result = $jwtObj::checkToken($token);
            if(!$result){
                $this->fail('身份认证失效');
            }
            $userData = (array)$result['data'];
            $userName = $userData['username'];
            $userId = $userData['user_id'];
            $redisUserToken = Cache::store('redisLogin')->get(config('redis.token').$userName);
            if(!$redisUserToken){
                 $this->fail('身份认证失效');
            }
            if($redisUserToken != $token ){
                $this->fail('身份认证失效');
            }

            //将得到的用户id 放到请求信息中去  方便后续使用
//            $this->request->post(['id'=>$userId]);
//            $this->request->get(['id'=>$userId]);
            $this->request->userId = $userId;



        }


    }

    /**
     * 通用响应
     * @param int $code 错误码
     * @param string $msg 错误描述
     * @param array $data 返回数据
     */
    public function response($code=200, $msg='success', $data=[])
    {
        $res = [
            'code' => $code,
            'msg' => $msg,
            'data' => $data
        ];
        //以下两行二选一
        //echo json_encode($res, JSON_UNESCAPED_UNICODE);die;
        json($res)->send();die;
    }
    /**
     * 失败时响应
     * @param string $msg 错误描述
     * @param int $code 错误码
     */
    public function fail($msg='fail',$code=500)
    {
        return $this->response($code, $msg);
    }

    /**
     * 成功时响应
     * @param array $data 返回数据
     * @param int $code 错误码
     * @param string $msg 错误描述
     */
    public function ok($data=[], $code=200, $msg='success')
    {
        return $this->response($code, $msg, $data);
    }


}